﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.FxCop.Sdk;

namespace LINQtoFxCop.Core
{
  /// <summary>
  /// Writes the warning report the disk. This is only provied for testing purposes.
  /// </summary>
  internal class ReportingService
  {
    private const string _FILE_NAME = "Report.xml";
    private const string _ANALYSIS_TIMESTAMP_TOSTRING = "yyyy.MM.dd_HH.mm.ss";

    internal ReportingService()
    {}

    public void WriteToDisk(IEnumerable<KeyValuePair<string, ProblemCollection>> problems)
    {
      var reportTimeStamp = DateTime.Now;

      var problemReport = new XElement("Report");

      foreach (var pair in problems.OrderBy(item => item.Key))
      {
        var ruleElement = new XElement(pair.Key,
          new XAttribute("NumberOfItems", pair.Value.Count));

        foreach (var problem in pair.Value)
        {
          var arg0 = problem.Resolution.Items[0] ?? string.Empty;
          var arg1 = problem.Resolution.Items[1] ?? string.Empty;
          var arg2 = problem.Resolution.Items[2] ?? string.Empty;
          var arg3 = problem.Resolution.Items[3] ?? string.Empty;

          ruleElement.Add(new XElement("x",
              new XAttribute("result", arg0),
              new XAttribute("name", arg1),
              new XAttribute("fullname", arg2),
              new XAttribute("nodetype", arg3)
              ));
        }
        problemReport.Add(ruleElement);
      }
      using (var sw = new StreamWriter(reportTimeStamp.ToString(_ANALYSIS_TIMESTAMP_TOSTRING) + "_" + _FILE_NAME, true))
      {
        problemReport.Save(sw);
      }
    }
  }
}
